package com.ahm.server.config.component;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author anhaimeng
 * @title: CustomUrlDescionManager
 * @projectName yeb001
 * @description: TODO
 * @date 2021/9/2414:32
 */
/*功能描述
 * @author ahm
 */
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        // 获取菜单对应的角色列表
        for (ConfigAttribute configAttribute : configAttributes) {

            String roleName = configAttribute.getAttribute();
            // 若登录进行访问
            if ("ROLE_LOGIN".equals(roleName)){
                // 如果是匿名登陆 抛出异常
                if (authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("尚未登录");
                }else {
                    return;
                }
            }
            // 获取用户对应的角色列表
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (roleName.equals(authority.getAuthority())){
                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足，请联系管理员");

    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
